<template>
  <el-card v-if="user">
    <el-form :model="user" label-width="80px">
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <img v-if="user.avatar" :src="user.avatar" class="avatar"/>
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="user.name"/>
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="user.phone"/>
      </el-form-item>
      <el-form-item label="地址">
        <el-input v-model="user.address"/>
      </el-form-item>
      <el-button type="primary" @click="saveUser">保存</el-button>
    </el-form>
    <el-divider/>
    <el-form :model="pwdForm" label-width="80px">
      <el-form-item label="新密码">
        <el-input v-model="pwdForm.password" type="password"/>
      </el-form-item>
      <el-button type="primary" @click="changePassword">修改密码</el-button>
    </el-form>
  </el-card>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getCurrentUser, updateUser, changeUserPassword } from '@/api/user'
import { ElMessage } from 'element-plus'

const user = ref(null)
const pwdForm = ref({ password: '' })

onMounted(async () => {
  const res = await getCurrentUser()
  user.value = res.data
})

const uploadUrl = computed(() => user.value ? `/api/users/${user.value.id}/avatar` : '')

function handleAvatarSuccess(res) {
  user.value.avatar = res.data.url
  ElMessage.success('头像上传成功')
}

async function saveUser() {
  await updateUser(user.value.id, user.value)
  ElMessage.success('保存成功')
}

async function changePassword() {
  await changeUserPassword(user.value.id, pwdForm.value.password)
  ElMessage.success('密码修改成功')
  pwdForm.value.password = ''
}
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 80px;
  height: 80px;
  display: block;
  border-radius: 50%;
}
.avatar-uploader-icon {
  font-size: 32px;
  color: #8c939d;
  width: 80px;
  height: 80px;
  line-height: 80px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
}
</style> 